<template>
  <div class="app-container">
    <el-form class="formList" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <!-- <el-row>
        <el-col :span="8"> -->
      <el-form-item label="批次编号" prop="batchNo">
        <el-input v-model="queryParams.batchNo" placeholder="请输入批次编号" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item style="margin-left: 22px">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      <!-- </el-col>
    </el-row> -->
    </el-form>
    <el-row class="row-mbinfo" style="margin-left: 0px; margin-right: 0px">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['activity:batch:add']">新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <!--          <el-button-->
          <!--            type="success"-->
          <!--            plain-->
          <!--            icon="el-icon-edit"-->
          <!--            size="mini"-->
          <!--            :disabled="single"-->
          <!--            @click="handleUpdate"-->
          <!--            v-hasPermi="['activity:batch:edit']"-->
          <!--          >修改-->
          <!--          </el-button>-->
        </el-col>
        <el-col :span="1.5">
          <!--          <el-button-->
          <!--            type="danger"-->
          <!--            plain-->
          <!--            icon="el-icon-delete"-->
          <!--            size="mini"-->
          <!--            :disabled="multiple"-->
          <!--            @click="handleDelete"-->
          <!--            v-hasPermi="['activity:batch:remove']"-->
          <!--          >删除-->
          <!--          </el-button>-->
        </el-col>
        <el-col :span="1.5">
          <!--          <el-button-->
          <!--            type="warning"-->
          <!--            plain-->
          <!--            icon="el-icon-download"-->
          <!--            size="mini"-->
          <!--            @click="handleExport"-->
          <!--            v-hasPermi="['activity:batch:export']"-->
          <!--          >导出-->
          <!--          </el-button>-->
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-row>

    <div class="divTable">
      <el-table border v-loading="loading" :data="batchList" @selection-change="handleSelectionChange">
        <!--        <el-table-column type="selection" width="55" align="center"/>-->
        <el-table-column label="批次编号" align="center" prop="batchNo" width="200" :show-overflow-tooltip="true" />
        <el-table-column label="兑换类型" align="center" prop="cardTypeStr" width="120" :show-overflow-tooltip="true" />
        <el-table-column label="兑换详情" align="center" prop="name" min-width="150px" :show-overflow-tooltip="true" />
        <el-table-column label="sku" align="center" prop="skuName" min-width="100px" :show-overflow-tooltip="true" />

        <el-table-column label="发行数量" align="center" prop="cardNumber" width="120" :show-overflow-tooltip="true" />
        <el-table-column label="领取时间" align="center" prop="timeStr" width="260px" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.startDate, "{y}年{m}月{d}日") }}-
              {{ parseTime(scope.row.endDate, "{y}年{m}月{d}日") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" width="170px" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="170px" :show-overflow-tooltip="true" />

        <el-table-column label="创建人" align="center" prop="createName" width="100" :show-overflow-tooltip="true" />
        <el-table-column label="数据状态" align="center" prop="totalAmount" width="100" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.dataStatus" active-value="1" inactive-value="0"
              @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>

        <!--        <el-table-column label="开始领取时间" align="center" prop="startDate" width="180">-->
        <!--          <template slot-scope="scope">-->
        <!--            <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="截止领取时间" align="center" prop="endDate" width="180">-->
        <!--          <template slot-scope="scope">-->
        <!--            <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['activity:batch:edit']">详细
            </el-button>
            <el-button v-if="scope.row.dataStatus == '0'" size="mini" type="text" icon="el-icon-delete"
              @click="handleDelete(scope.row)" v-hasPermi="['activity:batch:remove']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <!-- 添加或修改礼品卡管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="910px" append-to-body @keyup.enter.native="submitForm"
      z-index="1300">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="兑换码类型" required style="margin-bottom: 10px;">

          <el-radio style="margin-top: 12px" v-model="form.cardType" label="coupon">优惠券</el-radio>

          <el-radio style="margin-top: 12px" v-model="form.cardType" label="card">套餐卡</el-radio>

          <el-radio style="margin-top: 15px" v-model="form.cardType" label="service">服务项目</el-radio>
          <el-radio style="margin-top: 15px" v-model="form.cardType" label="product">商品</el-radio>

          <!-- <a v-if="form.cardType == 'product'"
            style="color: #155bd4"
            @click="selectCommodity">选择商品</a> -->
          <!-- 已选商品表格组件 -->
        </el-form-item>

        <div>
          <!-- 选择服务项目 -->
          <div v-if="form.cardType == 'service'">
            <el-button style="margin: 0px 0 10px 10px;" type="primary" size="small"
              @click="selectCommodityService">选择服务项目</el-button>
            <div style="margin: 10px;">
              <selectedA ref="childStore" style="margin-top: 10px;" v-if="Object.keys(this.selectedDataStore).length > 0"
                :selectedData="selectedDataStore" @tabRespon="tabRespon">
              </selectedA>
            </div>
          </div>
          <!-- 选择优惠券 -->
          <div v-if="form.cardType == 'coupon'">
            <el-button style="margin: 0px 0 10px 10px;" type="primary" size="small"
              @click="selectCommodityCoupon">选择优惠券</el-button>
            <div style="margin: 10px;">
              <selectedCoupon ref="childCoupon" style="margin-top: 10px;"
                v-if="Object.keys(this.selectedDataCoupon).length > 0" :selectedData="selectedDataCoupon"
                @tabRespon="tabResponCoupon">
              </selectedCoupon>
            </div>
          </div>

          <!-- 选择套餐卡 -->
          <div v-if="form.cardType == 'card'">
            <el-button style="margin: 0px 0 10px 10px;" type="primary" size="small"
              @click="selectCommodityCard">选择套餐卡</el-button>
            <div style="margin: 10px;">
              <selectedCard ref="childCard" style="margin-top: 10px;" v-if="Object.keys(this.selectedDataCard).length > 0"
                :selectedData="selectedDataCard" @tabRespon="tabResponCard">
              </selectedCard>
            </div>
          </div>

          <!-- 选择商品 -->
          <div v-if="form.cardType == 'product'">
            <el-button style="margin: 0px 0 10px 10px;" type="primary" size="small"
              @click="selectCommodityProduct">选择商品</el-button>
            <div style="margin: 10px;">
              <SelectedPro ref="childProduct" style="margin-top: 10px;"
                v-if="Object.keys(this.selectedDataProduct).length > 0" :selectedData="selectedDataProduct"
                @tabRespon="tabResponProduct"></SelectedPro>
            </div>
          </div>
        </div>

        <el-form-item label="发行数量" prop="cardNumber">
          <el-col :span="12">
            <el-input v-model="form.cardNumber" :min="1" :max="2000" maxlength="4" placeholder="请输入发行数量"
              @input="form.cardNumber = onInput(form.cardNumber, 0)" style="width: 330px" />
          </el-col>
        </el-form-item>

        <el-form-item label="领取时间" prop="startDate">
          <el-col :span="12">
            <div>
              <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="getTime" type="datetimerange"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions0"
                @blur="timeAssignment" style="width: 330px">
              </el-date-picker>
            </div>
          </el-col>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-col :span="12">
            <el-input v-model="form.remark" maxlength="200" placeholder="请输入备注" style="width: 350px" />
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="addButton" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--    &lt;!&ndash; 添加或修改礼品 &ndash;&gt;-->
    <!--    <el-dialog :title="title" :visible.sync="cardOpen" :batchIdStr="batchId" width="1300px" append-to-body-->
    <!--               @keyup.enter.native="submitForm">-->
    <!--      <card :batch="batchData" v-if="cardOpen"></card>-->
    <!--      <div slot="footer" class="dialog-footer">-->
    <!--        <el-button type="primary" @click="cardOpen=false">确 定</el-button>-->
    <!--        <el-button @click="cardOpen=false">取 消</el-button>-->
    <!--      </div>-->
    <!--    </el-dialog>-->

    <commodityCoupon v-if="couponOpen" @toCloseBox="toCloseBoxCoupon" @multipleSelection="multipleSelectionCoupon"
      :flag="couponOpen" :source="false" ref="selTableCoupon"></commodityCoupon>

    <commodityCard v-if="cardAOpen" @toCloseBox="toCloseBoxCard" @multipleSelection="multipleSelectionCard"
      :flag="cardAOpen" :source="false" ref="selTableCard"></commodityCard>

    <commodityPro v-if="productOpen" @toCloseBox="toCloseBoxProduct" @multipleSelection="multipleSelectionProduct"
      :flag="productOpen" :source="false" ref="selTableProduct" />

    <commodityItem v-if="storeOpen" @toCloseBox="toCloseBoxStore" @multipleSelection="multipleSelectionStore"
      :flag="storeOpen" :source="false" ref="selTable"></commodityItem>

    <commoditytab v-if="openA" @toCloseBox="toCloseBox" @multipleSelection="multipleSelection" :flag="openA"
      :proUids="proUids" ref="selTable"></commoditytab>

  </div>
</template>

<script>
import {
  listBatch,
  getBatch,
  delBatch,
  addBatch,
  updateBatch,
  updateDataStatus,
} from "@/api/activity/giftBatch";
import { onInput } from "@/utils/util";
import commoditytab from "@/components/Activity/commodityTab";
import SelectedPro from "@/components/radio/SelectedPro";
import selectedA from "@/components/radio/SelectedItem";
import commodityItem from "@/components/radio/commodityItem";

import selectedCoupon from "@/components/radio/SelectedCoupon";
import commodityCoupon from "@/components/radio/commodityCoupon";
import SelectedCard from "@/components/radio/SelectedCard";
import commodityCard from "@/components/radio/commodityCard";
import commodityPro from "@/components/radio/commodityPro";
import card from "./card";

//验证卡券
let checkCardNumber = (rule, value, callback) => {
  if (value > 2000) {
    callback(new Error());
  } else {
    callback();
  }
};

export default {
  name: "Batch",
  components: {
    card, commoditytab, SelectedPro, selectedA,
    commodityItem,
    selectedCoupon,
    commodityCard,
    SelectedCard,
    commodityCoupon,
    commodityPro
  },
  data () {
    return {

      storeOpen: false,
      selectedDataStore: {},
      couponOpen: false,
      selectedDataCoupon: {},
      cardAOpen: false,
      selectedDataCard: {},

      //添加卡券确认按钮
      addButton: false,
      //领取时间
      getTime: [],
      //选中的批次对象
      batchData: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 礼品卡管理表格数据
      batchList: [],
      // 弹出层标题
      title: "",
      //查看详细标题
      viewTitle: "",
      // 是否显示弹出层
      open: false,
      openA: false,
      //修改弹出层
      cardOpen: false,
      //是否显示查看详细弹出层
      viewOpen: false,
      //查看详细数据
      showData: [],
      // 数据状态字典
      dataStatusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        batchNo: null,
        startDate: null,
        endDate: null,
      },
      proUids: [], //排除商品，活动用到
      selectedData: [],
      // 商品
      productOpen: false,
      selectedDataProduct: {},

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        cardNumber: [
          { required: true, message: "请输入发行数量", trigger: "blur" },
          {
            min: 1,
            max: 4,
            message: "发行数量在 1 到 2000 之间",
            trigger: "blur",
          },
          {
            type: "number",
            validator: checkCardNumber,
            message: "发行数量在 1 到 2000 之间",
          },
        ],
        cardAmount: [
          { required: true, message: "请输入发卡金额", trigger: "blur" },
          {
            min: 1,
            max: 4,
            message: "发卡金额 1 到 2000 元之间",
            trigger: "blur",
          },
          {
            type: "number",
            validator: checkCardNumber,
            message: "发卡金额 1 到 2000 元之间",
          },
        ],
        startDate: [
          { required: true, message: "请选择领取日期", trigger: "blur" },
        ],
      },



      pickerOptions0: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
    };
  },
  created () {
    this.getList();
    this.getDicts("sys_data_status").then((response) => {
      this.dataStatusOptions = response.data;
    });
  },
  methods: {
    tabResponCard () {
      this.selectedDataCard = {}
    },
    tabResponCoupon () {
      this.selectedDataCoupon = {}
    },
    tabRespon () {
      this.selectedDataStore = {}
    },
    tabResponProduct () {
      this.selectedDataProduct = {}
    },
    /** 查询礼品卡管理列表 */
    getList () {
      this.loading = true;
      listBatch(this.queryParams).then((response) => {
        this.batchList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    selectCommodityService () {
      this.$forceUpdate();
      this.storeOpen = true;
      this.$nextTick(() => {
        this.$refs["selTable"].greet(this.selectedDataStore);
      });
    },

    //优惠券
    selectCommodityCoupon () {
      this.$forceUpdate()
      this.couponOpen = true;
      this.$nextTick(() => {
        this.$refs["selTableCoupon"].greet(this.selectedDataCoupon);
      });
    },

    selectCommodityCard () {
      this.$forceUpdate()
      this.cardAOpen = true;
      this.$nextTick(() => {
        this.$refs["selTableCard"].greet(this.selectedDataCard);
      });
    },

    selectCommodityProduct () {
      this.productOpen = true;
      this.$nextTick(() => {
        this.$refs["selTableProduct"].greet(this.selectedDataProduct);
      });
    },

    multipleSelectionCoupon (data) {
      this.couponOpen = false
      this.selectedDataCoupon = data;
      this.$nextTick(() => {
        this.$refs.childCoupon.getList();
      });
    },

    multipleSelectionCard (data) {
      this.cardAOpen = false
      this.selectedDataCard = data;
      this.$nextTick(() => {
        this.$refs.childCard.getList();
      });
    },

    multipleSelectionProduct (data) {
      this.productOpen = false
      this.selectedDataProduct = data;
      this.$nextTick(() => {
        this.$refs.childProduct.getList();
      });
    },

    toCloseBoxCoupon () {
      this.couponOpen = false;
    },

    toCloseBoxCard () {
      this.cardAOpen = false;
    },

    toCloseBoxProduct () {
      this.productOpen = false;
    },

    toCloseBoxStore () {
      this.couponOpen = false;
    },

    toCloseBox () {
      this.open = false;
    },

    multipleSelection (data) {
      this.openA = false;
      this.selectedData = data;
      // this.$nextTick(() => {
      //   this.$refs.child.getList();
      // });
    },

    multipleSelectionStore (data) {

      this.storeOpen = false
      this.selectedDataStore = data;
      this.$nextTick(() => {
        this.$refs.childStore.getList();
      });
    },

    onInput,
    // 数据状态字典翻译
    dataStatusFormat (row, column) {
      return this.selectDictLabel(this.dataStatusOptions, row.dataStatus);
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },

    //调用子组件中方法，向子组件传值
    selectCommodity () {
      this.$forceUpdate();
      this.openA = true;
      this.$nextTick(() => {
        this.$refs["selTable"].greet(this.selectedData);
      });
    },

    // 表单重置
    reset () {
      this.form = {
        batchId: null,
        batchNo: null,
        customerUid: null,
        customerName: null,
        cardType: null,
        dataStatus: null,
        cardNumber: null,
        remark: null,
        cardAmount: null,
        totalAmount: null,
        createTime: null,
        createUser: null,
        updateTime: null,
        updateUser: null,
        startDate: null,
        endDate: null,
      };
      this.selectedDataStore = {}
      this.selectedDataCoupon = {}
      this.selectedDataCard = {}
      this.selectedDataProduct = {}
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map((item) => item.batchId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.getTime = [];
      this.addButton = false;
      this.reset();
      this.open = true;
      this.title = "新增兑换码";
    },
    /** 查看详情按钮操作 **/
    handleShowDetail (row) { },
    handCloseDetail () {
      this.viewOpen = false;
      this.showData = [];
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.$router.push("/gift/card/data/" + row.batchId);
    },
    /** 提交按钮 */
    submitForm () {
      this.form.startDate = this.getTime[0];
      this.form.endDate = this.getTime[1];

      // 兑换码类型

      if (this.form.cardType == 'coupon') {
        // 获取id this.selectedDataCoupon
        this.form.cardObjectId = this.selectedDataCoupon.couponUid;
        if (this.form.cardObjectId == null) {
          this.msgError("请选择优惠券数据");
          return
        }
      } else if (this.form.cardType == 'card') {
        // 获取id  this.selectedDataCard
        this.form.cardObjectId = this.selectedDataCard.cardId;
        if (this.form.cardObjectId == null) {
          this.msgError("请选择套餐卡数据");
          return
        }
      } else if (this.form.cardType == 'service') {
        // 获取id  this.selectedDataStore
        this.form.cardObjectId = this.selectedDataStore.itemId;
        this.form.skuId = this.selectedDataStore.skuId
        this.selectedDataStore.proboxServiceItemSkus.forEach(item => {
          if (item.skuId == this.form.skuId) {
            this.form.skuName = item.skuName
          }
        })
        if (this.form.cardObjectId == null) {
          this.msgError("请选择服务项目数据");
          return
        }
      } else if (this.form.cardType == 'product') {
        // 获取id  this.selectedDataProduct
        this.form.cardObjectId = this.selectedDataProduct.productUid;
        if (this.form.cardObjectId == null) {
          this.msgError("请选择商品数据");
          return
        }
      }

      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.addButton = true;
          if (this.form.batchId != null) {
            updateBatch(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.selectedDataCard = {}
              this.selectedDataCoupon = {}
              this.selectedDataStore = {}
              this.selectedDataProduct = {}
            });
          } else {
            addBatch(this.form).then((response) => {
              this.addButton = false;
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.selectedDataCard = {}
              this.selectedDataCoupon = {}
              this.selectedDataStore = {}
              this.selectedDataProduct = {}
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const batchIds = row.batchId || this.ids;
      this.$confirm(
        '是否确认删除礼品卡管理编号为"' + batchIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delBatch(batchIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download(
        "activity/batch/export",
        {
          ...this.queryParams,
        },
        `activity_batch.xlsx`
      );
    },
    // 状态修改
    handleStatusChange (row) {
      let text = row.dataStatus === "0" ? "无效" : "有效";
      this.$confirm(
        '确定要把批次编号："' + row.batchNo + '"设为' + text + "吗？",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return updateDataStatus(row.batchId, row.dataStatus);
        })
        .then(() => {
          this.msgSuccess("操作成功");
          this.getList();
        })
        .catch(function () {
          row.dataStatus = row.dataStatus === "0" ? "1" : "0";
        });
    },
    timeAssignment (row) {
      this.form.startDate = this.getTime[0];
      this.form.endDate = this.getTime[1];
    },
  },
};
</script>
